package com.itheima.reggie.aop;

import com.itheima.reggie.common.BaseContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
//运用aop对公共字段进行自动填充
@Aspect
@Component
public class CommonColumnAdvice {

  /* //对哪些类或方法进行增强， 切入点表达式
    @Pointcut("execution(* com.itheima.reggie.controller.*Controller.save*(..) )" +
            "||" + "execution(* com.itheima.reggie.controller.*Controller.update*(..))")
    public void pt() {
    }

    //增强的功能，对四个字段的值进行自动填充
    @Around("pt()")
    public Object modifyColumn(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = null;

        //拿到employee 参数对象
        Object[] args = pjp.getArgs();
        Object obj = args[0];   //约定方法的第一个参数为实体类对象
        Class<?> aClass = obj.getClass();
        String methodName = pjp.getSignature().getName();

        Method setUpdateTime = aClass.getMethod("setUpdateTime", LocalDateTime.class);
        setUpdateTime.invoke(obj, LocalDateTime.now());

        Method setUpdateUser = aClass.getMethod("setUpdateUser", Long.class);
        setUpdateUser.invoke(obj, BaseContext.getCurrentId());
        if (methodName.startsWith("save")) {
            //拿到setCreateTime方法，设置创造时间
            Method setCreateTime = aClass.getMethod("setCreateTime", LocalDateTime.class);
            setCreateTime.invoke(obj, LocalDateTime.now());

            Method setCreateUser = aClass.getMethod("setCreateUser", Long.class);
            setCreateUser.invoke(obj, BaseContext.getCurrentId());
        }
        proceed = pjp.proceed(args);

        return proceed;
    }*/
}
